package cn.taobaoke.restful.controller.admin;

import cn.taobaoke.restful.controller.BaseController;
import cn.taobaoke.restful.domain.AdminEntity;
import cn.taobaoke.restful.interceptor.Auth;
import cn.taobaoke.restful.service.AdminService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yangzuo
 * @since 2017-03-11
 */
@RestController
@RequestMapping("/{domain}/{domainId}/api/admins")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AdminEndpoint extends BaseController {

    @Auth(type = Auth.AuthType.ADMIN)
    @DeleteMapping("/{adminId}")
    public Result deleteAdministrator(@PathVariable Long domainId, @PathVariable Long adminId) {
        logger.debug("删除管理员操作: DELETE /{}/api/admins/{}", domainId, adminId);
        adminService.deleteAdminEntity(adminId, domainId);
        return wrapVoid();
    }

    @Auth(type = Auth.AuthType.ADMIN)
    @PutMapping("")
    public Result addAdmin(@PathVariable Long domainId, @RequestBody AdminEntity admin) {
        if (admin.getId() == null) {
            logger.debug("添加管理员操作: PUT /{}/api/admins \n{}", domainId, admin);
            admin = adminService.insertAdminEntity(admin, domainId);
        } else {
            logger.debug("更新管理员操作: PUT /{}/api/admins \n{}", domainId, admin);
            admin = adminService.updateAdminEntity(admin, domainId);
        }
        return wrapObj(admin);
    }

    @Auth(type = Auth.AuthType.ADMIN)
    @GetMapping("")
    public Result getAdmins(@PathVariable Long domainId) {
        logger.debug("获取管理员列表操作: GET /{}/api/admins", domainId);
        List<AdminEntity> adminList = adminService.getAll(domainId);
        return wrapObj(adminList);
    }

    private final @NonNull AdminService adminService;

    private static Logger logger = LogManager.getLogger(AdminEndpoint.class);
}
